package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author yu yang
 * @date 2022/9/27 -21:44
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String parentPath;
    //文件上传
    @PostMapping("/upload")
    public R<String> uploadFile(@RequestPart("file") MultipartFile file) throws IOException {
        //file只是一个暂存文件，请求结束后自动删除

        if (!file.isEmpty()) {
            //文件原始名称
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            File dir = new File(parentPath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            file.transferTo(new File(parentPath + fileName));
            return R.success(fileName);
        }
        return R.error("文件不能为空");
    }
    //文件下载
    @GetMapping("/download")
    public void download(@RequestParam("name") String filename, HttpServletResponse response) {
        try {
            FileInputStream inputStream = new FileInputStream(parentPath + filename);
            ServletOutputStream outputStream  = response.getOutputStream();
            response.setContentType("image/jpeg");
//            int len = 0;
//            byte[] bytes = new byte[1024];
//            while ((len = inputStream.read(bytes)) != -1) {
//                outputStream.write(bytes, 0, len);
//                outputStream.flush();
//            }
            FileCopyUtils.copy(inputStream,outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
